<template>
    <div class="baseInfoSet">
        <form @submit="formSubmit" class="baseInfoForm">
            <view class="uni-form-item uni-column">
                <button 
                    @chooseavatar="chooseavatar"
                    open-type="chooseAvatar"
                    role="button"
                    aria-disabled="false"
                    class="avatar-wrapper"
                >
                    <view  class="imgAvatar">

                        <image 
                            src="~@/static/images/defaultHead.jpg" 
                            class="defaultHeadPic"
                            v-if="updateForm.avatarUrl==''"
                        />
                        <image 
                            :src="updateForm.avatarUrl" 
                            class="defaultHeadPic"
                            v-else
                        />
                        <uni-icons type="upload-filled" size="20" class="uploadIcon"></uni-icons>
                    </view>
                </button>
            </view>
            <view class="uni-form-item uni-column">
                <uni-forms ref="baseForm" class="baseForm">
                    <uni-forms-item label="用户名" >
                        <uni-easyinput 
                            v-model="updateForm.nickname" 
                            type="nickname" 
                            placeholder="请输入用户名" 
                            :maxlength="20"
                            @change="onChange"
                        />
                    </uni-forms-item>
                    <uni-forms-item label="手机号" >
                        <div class="flexStyleBetween">
                            <uni-easyinput v-model="updateForm.phoneNumber" type="number" confirmType="done" placeholder="请输入手机号" :maxlength="11"/>
                            <button 
                                open-type="getPhoneNumber" 
                                @getphonenumber="getUserPhoneNumber" 
                                class="phone-number-wrapper"
                            >
                                一键获取
                            </button>   
                        </div>
                    </uni-forms-item>
                </uni-forms>
            </view>

            <view class="uni-form-item uni-column">
                <div class="confimBox">
                    <button
                        class="confimBtn"
                        :class="{'disabled':!isAvailable}"
                        form-type="submit"
                    >
                        确认保存
                    </button>
                </div>
            </view>

        </form>

    </div>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import { objectAny } from "../../options/base"
import { myUserStore } from "../../store";
import { goToBack, showModal, showToast } from "../../utils/utils";


const clientUserManage = uniCloud.importObject(`client-user-manage`, {customUI: true});
const userStore=myUserStore()

let submitStatus:'fulfilled'|'pending'='fulfilled';     //请求提交状态
let wxPhoneNumber=``;       //用户授权后的微信手机号
const isAvailable=ref(false);       //当前是否可以提交资料
const updateForm=ref<{
    phoneNumber:string; //手机号码
    nickname:string;    // 用户名
    avatarUrl:string;   // 用户头像地址
}>({
    phoneNumber:userStore.myUser.mobile,     
    nickname:userStore.myUser.nickname,        
    avatarUrl:userStore.myUser.avatarUrl   
})

watch(updateForm.value,(value)=>{
    if(value.nickname.trim()!==''){
        if(value.phoneNumber.trim()===``){
            return isAvailable.value=false
        }
        if(wxPhoneNumber===value.phoneNumber){      // 使用的授权手机号时 直接返回正确
            return isAvailable.value=true
        }
        if(/^1[3-9]\d{9}$/.test(value.phoneNumber)){
            return isAvailable.value=true
        }
    }
    return isAvailable.value=false
},{
    immediate:true
})

async function formSubmit(){
	console.log(isAvailable.value, "=isAvailable.value")
    if(!isAvailable.value){
        return showModal({
            title:`操作提示`,
            content:`请先填写完整资料信息`,
            showCancel:false
        })
    }
    if(submitStatus ===`pending`){
        return console.log(`======> formSubmit 正在提交数据，无需多次提交，本次提交取消<======`)
    }
    submitStatus=`pending`;

    try {
        uni.showLoading({
            title: '正在保存'
        });
		console.log(updateForm, '----updateForm---')
        const {myErrCode,errMsg}=await clientUserManage.setUserInfo(updateForm.value)
        uni.hideLoading();
        if(myErrCode!==0){
            submitStatus=`fulfilled`
            return showModal({
                title:`异常提示`,
                content:errMsg,
                showCancel:false
            })
        }
        await showToast(`保存成功`,`success`,true,1500)
        setTimeout(()=>{
            goToBack();
        },1500)
    } catch (error) {
        submitStatus=`fulfilled`
        console.error(error);
        uni.hideLoading();
        showModal({
            title:`异常提示`,
            content:`保存失败，请稍后再试`,
            showCancel:false
        })
    }
}

    function chooseavatar(info:objectAny){
        const avatarUrl=info.detail.avatarUrl
        updateForm.value.avatarUrl=avatarUrl;
        uni.setStorageSync(`wxAvatarUrl`,avatarUrl);
    }
    async function getUserPhoneNumber(e:objectAny){
        const code=e.detail.code
        if(code){
            try {
                uni.showLoading({
                    title: '正在加载'
                });
                const {myErrCode,errMsg,data:{phoneNumber}}= await clientUserManage.wxCodeGeUserPhoneNumber(code);
                if(myErrCode!==0){
                    return showModal({
                        title:`异常提示`,
                        content:errMsg,
                        showCancel:false
                    })
                }
                wxPhoneNumber=phoneNumber;
                updateForm.value.phoneNumber=phoneNumber
            } catch (error) {
                console.error(error)
                showModal({
                    title:`异常提示`,
                    content:`系统繁忙请稍后再试`,
                    showCancel:false
                })
            }
            uni.hideLoading();
        }
    }

</script>

<style lang="stylus" scoped>
@import './userinfo.styl';

.baseInfoSet
    padding: 20rpx
    padding-top: 80rpx
    box-sizing: border-box
    display: flex
    justify-content: center
    .baseInfoForm
        width: 90%
    .avatar-wrapper
        margin-bottom: 60rpx
        display: flex;
        align-items: center;
        justify-content: center;
    .phone-number-wrapper
        font-size: 12px
        display: flex
        align-items: center
        color: #fff
        margin-left: 30rpx
        background-color: #f37000
        padding: 0 20rpx
    .imgAvatar
        position relative
        .uploadIcon
            position: absolute
            bottom: -32rpx
            right: 0
    .confimBox
        width: 100%
        margin-top: 200rpx
</style>